package com.vf.web.controller.system;

import java.io.UnsupportedEncodingException;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.spec.AlgorithmParameterSpec;
import java.util.Arrays;
import java.util.List;
import java.util.Set;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.vf.common.annotation.Anonymous;
import com.vf.common.config.WxAppConfig;
import com.vf.common.core.domain.entity.WxLoginBody;
import com.vf.common.utils.sign.Base64;
import com.vf.system.domain.dto.UserLoginDTO;
import com.vf.system.domain.vo.WxInfo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import com.vf.common.constant.Constants;
import com.vf.common.core.domain.AjaxResult;
import com.vf.common.core.domain.entity.SysMenu;
import com.vf.common.core.domain.entity.SysUser;
import com.vf.common.core.domain.model.LoginBody;
import com.vf.common.utils.SecurityUtils;
import com.vf.framework.web.service.SysLoginService;
import com.vf.framework.web.service.SysPermissionService;
import org.springframework.web.client.RestTemplate;
import com.vf.system.service.ISysMenuService;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

import static com.vf.common.core.domain.AjaxResult.success;
import static com.vf.framework.datasource.DynamicDataSourceContextHolder.log;


/**
 * 登录验证
 * 
 * @author ruoyi
 */
@RestController
@Api(tags = "登录接口")
public class SysLoginController
{
    @Autowired
    private SysLoginService loginService;

    @Autowired
    private ISysMenuService menuService;

    @Autowired
    private SysPermissionService permissionService;

    @Autowired
    private RestTemplate restTemplate;



    @PostMapping("/wxLogin")
    @ApiOperation(value = "微信登录")
    @Anonymous
    public AjaxResult wxLogin(@RequestBody WxLoginBody loginBody)
    {
        log.info("登录参数：" + JSON.toJSONString(loginBody));
        log.info("code：" + loginBody.getCode());

        String code = loginBody.getCode();
        JSONObject userInfo = loginBody.getUserInfo();

        if (StringUtils.isEmpty(code) || userInfo == null) {
            return AjaxResult.error("缺少必要参数");
        }

        // 调用微信接口获取 session_key 和 openid
        String url = "https://api.weixin.qq.com/sns/jscode2session?appid=" + WxAppConfig.APPID +
                "&secret=" + WxAppConfig.APPSecret +
                "&js_code=" + code +
                "&grant_type=authorization_code";

        String res = restTemplate.getForObject(url, String.class);
        JSONObject jsonObject = JSON.parseObject(res);

        String sessionKey = jsonObject.getString("session_key");
        String openid = jsonObject.getString("openid");

        if (StringUtils.isEmpty(sessionKey)) {
            return AjaxResult.error("获取 session_key 失败");
        }

        // 假设 userInfo 已经是明文（前端已处理加密）
        // 可以直接使用 userInfo 包含的信息注册或登录用户
        String nickName = userInfo.getString("nickName");
        String avatarUrl = userInfo.getString("avatarUrl");


        // 示例：生成 token 或执行业务逻辑
        UserLoginDTO userLoginDTO = loginService.wxLogin(new WxInfo(nickName, avatarUrl, openid));// 根据实际逻辑调整


        return success(userLoginDTO);
    }

    /**
     * AES解密
     * @param sessionKey
     * @param encryptedIv
     * @param encryptedData
     */
    private String decrypt(String sessionKey,String encryptedIv,String encryptedData) throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidAlgorithmParameterException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException, UnsupportedEncodingException {
        //转化为字节数组
        byte[] key = Base64.decode(sessionKey);
        byte[] iv = Base64.decode(encryptedIv);
        byte[] encData = Base64.decode(encryptedData);
        // 如果密钥不足16位，那么就补足
        int base = 16;
        if (key.length % base != 0) {
            int groups = key.length / base + (key.length % base != 0 ? 1 : 0);
            byte[] temp = new byte[groups * base];
            Arrays.fill(temp, (byte) 0);
            System.arraycopy(key, 0, temp, 0, key.length);
            key = temp;
        }

        // 如果初始向量不足16位，也补足
        if (iv.length % base != 0) {
            int groups = iv.length / base + (iv.length % base != 0 ? 1 : 0);
            byte[] temp = new byte[groups * base];
            Arrays.fill(temp, (byte) 0);
            System.arraycopy(iv, 0, temp, 0, iv.length);
            iv = temp;
        }

        AlgorithmParameterSpec ivSpec = new IvParameterSpec(iv);
        String resultStr = null;

        try {
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
            SecretKeySpec keySpec = new SecretKeySpec(key, "AES");
            cipher.init(Cipher.DECRYPT_MODE, keySpec, ivSpec);
            resultStr = new String(cipher.doFinal(encData), "UTF-8");
        } catch (Exception e) {
            log.info("解析错误！");
            e.printStackTrace();
        }

        //解析解密后的字符串
        return resultStr;
    }

    /**
     * 登录方法
     * 
     * @param loginBody 登录信息
     * @return 结果
     */
    @PostMapping("/login")
    public AjaxResult login(@RequestBody LoginBody loginBody)
    {
        AjaxResult ajax = success();
        // 生成令牌
        String token = loginService.login(loginBody.getUsername(), loginBody.getPassword(), loginBody.getCode(),
                loginBody.getUuid());
        ajax.put(Constants.TOKEN, token);
        return ajax;
    }

    /**
     * 获取用户信息
     * 
     * @return 用户信息
     */
    @GetMapping("getInfo")
    public AjaxResult getInfo()
    {
        SysUser user = SecurityUtils.getLoginUser().getUser();
        // 角色集合
        Set<String> roles = permissionService.getRolePermission(user);
        // 权限集合
        Set<String> permissions = permissionService.getMenuPermission(user);
        AjaxResult ajax = success();
        ajax.put("user", user);
        ajax.put("roles", roles);
        ajax.put("permissions", permissions);
        return ajax;
    }

    /**
     * 获取路由信息
     * 
     * @return 路由信息
     */
    @GetMapping("getRouters")
    public AjaxResult getRouters()
    {
        Long userId = SecurityUtils.getUserId();
        List<SysMenu> menus = menuService.selectMenuTreeByUserId(userId);
        return success(menuService.buildMenus(menus));
    }



}
